package org.galaxyworld.flycode.config;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FilenameUtils;

import java.util.HashMap;
import java.util.Map;

public class ConfigManager {

    private final Map<String, ConfigData> configDataMap = new HashMap<>();

    public static ConfigManager getInstance() {
        return ConfigManagerInstance.INSTANCE;
    }

    public static <T extends ConfigData> T getConfig(Class<T> tClass) {
        ConfigManager manager = ConfigManager.getInstance();
        if (tClass == AppConfigData.class) {
            return manager.get("app", tClass);
        } else if (tClass == JdbcConfigData.class) {
            return manager.get("jdbc", tClass);
        } else if (tClass == ModelConfigData.class) {
            return manager.get("model", tClass);
        } else if (tClass == ServiceConfigData.class) {
            return manager.get("service", tClass);
        } else {
            throw new RuntimeException("Unsupported config file.");
        }
    }

    private <T extends ConfigData> T get(String name, Class<T> tClass) {
        @SuppressWarnings("unchecked")
        T loaded = (T) configDataMap.get(name);
        if (loaded == null) {
            try {
                String configFilePath = FilenameUtils.separatorsToSystem(String.format("%s/config/%s.properties", System.getProperty("user.dir"), name));
                ConfigFile configFile = new ConfigFile(new PropertiesConfiguration(configFilePath));
                loaded = tClass.newInstance();
                loaded.load(configFile);
                configDataMap.put(loaded.getName(), loaded);
            } catch (ConfigurationException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return loaded;
    }

    private static final class ConfigManagerInstance {
        public static final ConfigManager INSTANCE = new ConfigManager();
    }

}
